package com.tarena.lbs.basic.web.service.impl;


import com.alibaba.fastjson2.JSONObject;
import com.tarena.lbs.attach.api.AttachApi;

import com.tarena.lbs.base.protocol.pager.BasePageList;
import com.tarena.lbs.base.protocol.pager.PageResult;
import com.tarena.lbs.basic.web.repository.UserRepository;
import com.tarena.lbs.basic.web.service.IEsService;
import com.tarena.lbs.basic.web.service.IUserService;
import com.tarena.lbs.common.attach.enums.BusinessTypeEnum;
import com.tarena.lbs.common.basic.constance.Const;
import com.tarena.lbs.common.passport.principle.UserPrinciple;
import com.tarena.lbs.common.security.utils.LbsSecurityContenxt;
import com.tarena.lbs.pojo.attach.dto.AttachDTO;
import com.tarena.lbs.pojo.attach.param.AttachUpdateParam;
import com.tarena.lbs.pojo.attach.query.AttachQuery;
import com.tarena.lbs.pojo.basic.bo.UserBO;
import com.tarena.lbs.pojo.basic.param.EsUpdateParam;
import com.tarena.lbs.pojo.basic.param.UserParam;
import com.tarena.lbs.pojo.basic.param.UserStoreParam;
import com.tarena.lbs.pojo.basic.query.UserQuery;
import com.tarena.lbs.pojo.basic.query.UserStoreQuery;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

@Service
@Slf4j
public class UserServiceImpl implements IUserService {

    @Resource
    private UserRepository userRepository;

    @Resource
    AttachApi attachApi;

    @Resource
    private IEsService iEsService;

    @Value("${app.attach.url}")
    private String url;

    @Override public BasePageList<UserBO> userList(UserQuery userQuery) {
        return userRepository.list(userQuery);
    }

    @Override
    public UserBO getDetail(Integer userId) {
        log.info("getDetail userId ={}",userId);
        UserPrinciple loginUser = LbsSecurityContenxt.getLoginToken();
        if (userId == null && loginUser != null) {
            userId = loginUser.getId();
        }
        UserBO userBO =  userRepository.getDetail(userId);
        //查询图片
        AttachQuery attachQuery = new AttachQuery();
        attachQuery.setBusinessType(BusinessTypeEnum.USER.getType());
        attachQuery.setBusinessId(userBO.getId());
        List<AttachDTO> attachInfo = attachApi.getAttachInfoByParam(attachQuery);
        StringBuffer userPicture = new StringBuffer();
        if (!CollectionUtils.isEmpty(attachInfo)) {
            attachInfo.forEach(attach -> userPicture.append(url + attach.getFileUuid()).append(","));
        }
        int lastIndex = userPicture.toString().lastIndexOf(",");
        userBO.setUserNickPicture(StringUtils.isEmpty(userPicture) ? "" : userPicture.toString().substring(0,lastIndex));
        return userBO;
    }

    @Override
    public void userInterest(UserStoreParam userStoreParam) throws Exception {
        EsUpdateParam param = new EsUpdateParam(null, Const.USER_INDEX_DATABASE_NAME);
        UserBO userBO = getDetail(userStoreParam.getStoreId());
        userBO.setUserId(userStoreParam.getUserId());
        //查询图片
        AttachQuery attachQuery = new AttachQuery();
        attachQuery.setBusinessType(BusinessTypeEnum.USER.getType());
        attachQuery.setBusinessId(userBO.getId());
        List<AttachDTO> attachInfo = attachApi.getAttachInfoByParam(attachQuery);
        StringBuffer userPicture = new StringBuffer();
        if (!CollectionUtils.isEmpty(attachInfo)) {
            attachInfo.forEach(attach -> userPicture.append(url + attach.getFileUuid()).append(","));
        }
        userBO.setUserNickPicture(userPicture == null ? "" : userPicture.toString());
        iEsService.insertData(param,userBO);
    }

    @Override
    public PageResult<UserBO> userInterestList(UserStoreQuery userStoreQuery) throws Exception {
        UserPrinciple loginUser = LbsSecurityContenxt.getLoginToken();
        if (loginUser != null) {
            userStoreQuery.setUserId(loginUser.getId());
        }
        SearchSourceBuilder builder = new SearchSourceBuilder();
        int page = userStoreQuery.getPageNo();
        int size = userStoreQuery.getPageSize();
        int from = (page - 1) * size;
        builder.from(from);
        builder.size(size);
        builder.query(QueryBuilders.termQuery("userId",userStoreQuery.getUserId()));
        List<UserBO> userBOList = new ArrayList<>();
        SearchResponse response = iEsService.search(Const.USER_INDEX_DATABASE_NAME,builder);
        for (int i = 0; i < response.getHits().getHits().length; i++) {
            SearchHit hit = response.getHits().getHits()[i];
            UserBO userBO = JSONObject.parseObject(hit.getSourceAsString(), UserBO.class);
            log.info("-----" + JSONObject.toJSONString(userBO));
            userBOList.add(userBO);
        }
        PageResult<UserBO> pageResult = new PageResult<>();
        pageResult.setObjects(userBOList);
        pageResult.setPageNo(userStoreQuery.getPageNo());
        pageResult.setPageSize(userStoreQuery.getPageSize());
        pageResult.setTotal(Long.valueOf(userBOList.size()));
        return pageResult;
    }

    @Override
    public Integer saveUserInfo(UserParam userParam) throws Exception {
        Integer id = userRepository.saveUserInfo(userParam);
        if (!StringUtils.isEmpty(userParam.getUserImage())) {
            createAttach(id, BusinessTypeEnum.USER.getType(), Arrays.asList(userParam.getUserImage()));
        }
        return id;
    }

    private void createAttach(Integer businessId,Integer businessType,List<String> fileIds) {
        List<AttachUpdateParam> attachUpdateParams = new ArrayList<>();
        fileIds.forEach(id -> {
            AttachUpdateParam updateParam = new AttachUpdateParam();
            updateParam.setId(Integer.valueOf(id));
            updateParam.setBusinessId(businessId);
            updateParam.setBusinessType(businessType);
            updateParam.setIsCover(0);
            attachUpdateParams.add(updateParam);
        });
        attachApi.batchUpdateAttachByIdList(attachUpdateParams);
    }
}
